<template>
  <div class="page-content">
    <a-card style="width: 100%; height: 100%">
      <div class="header">
        <a-space class="left" direction="vertical" :size="[8, 12]">
          <!-- <Condition
          :condition="condition"
          :btns="['reset']"
          @search="onSearch"
          @reset="conditionReset"
        ></Condition> -->
          <a-input-search
            v-model:value="noticeName"
            placeholder="请输入预警通知名称"
            style="width: 220px"
            @search="onSearch"
          />
          <div class="title">共筛选出 {{ pagination.total }} 条数据</div>
        </a-space>
        <a-space class="right" direction="vertical" :size="[8, 12]">
          <a-space>
            <a-button type="primary" @click="modalShow()">新建预警通知</a-button>
          </a-space>
        </a-space>
      </div>
      <div class="main">
        <a-table
          class="table"
          size="small"
          :loading="loading"
          :dataSource="List"
          :columns="columns"
          :pagination="pagination"
          @change="paginationChange"
          :sticky="{ offsetHeader: 0 }"
        >
          <template #bodyCell="{ column, text, index, record }">
            <template v-if="column.dataIndex === 'no'">
              {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
            </template>
            <template v-else-if="column.dataIndex === 'createTime'">
              {{ timeFilter(record[column.dataIndex]) }}
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <a-button type="link" @click="modalShow(record)">查看详情</a-button>
              <a-button type="link" @click="Del(record)">删除通知</a-button>
            </template>
            <template v-else>
              {{ text }}
            </template>
          </template>
        </a-table>
      </div>
      <a-modal
        width="1200px"
        :bodyStyle="store.userStore.bodyStyle"
        v-model:open="modal.open"
        :title="modal.title"
        ok-text="确认"
        cancel-text="取消"
        @ok="modalConfirm"
        :maskClosable="false"
      >
        <a-form
          class="modelForm"
          ref="modelForm"
          :colon="false"
          :model="formState"
          :label-col="{ style: { width: '140px' } }"
        >
          <a-row :gutter="[16, 0]">
            <a-col :span="8">
              <a-form-item
                label="预警通知名称："
                :label-col="{ style: { width: '110px' } }"
                name="noticeName"
                required
                :rules="[
                  {
                    required: true,
                    message: '预警通知名称不能为空',
                    trigger: 'change'
                  }
                ]"
              >
                <a-input
                  style="width: 350px"
                  :maxLength="50"
                  v-model:value="formState.noticeName"
                  autocomplete="off"
                  placeholder="请输入预警通知名称"
                  :disabled="modal.type === 'detail'"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8" />
            <a-col :span="8">
              <a-form-item
                v-if="formState.createTime"
                label="创建时间"
                :label-col="{ style: { width: '110px' } }"
              >
                {{ formState.createTime }}
              </a-form-item>
            </a-col>
          </a-row>
          <!-- <a-row class="title">
            <a-col :span="18"> <span class="red">*</span> 预警通知触发事件 </a-col>
          </a-row> -->
          <a-row class="title">
            <a-col :span="24" style=" padding-left: 16px;background-color: #f7f8fa">
              <span class="red">*</span> 预警通知触发事件
            </a-col>
          </a-row>
          <div style=" padding: 16px; margin-bottom: 24px;border: 1px solid rgb(229, 230, 235)">
            <a-row style="justify-content: space-between" :gutter="16">
              <a-col :span="16">
                <div style=" height: 100%; padding: 16px;border: 1px solid #e5e6eb">
                  <template v-for="(subitem, index) in formState.conditions" :key="index">
                    <a-form-item
                      :label="'条件' + numberToChinese(index + 1) + ':'"
                      :label-col="{ style: { width: '100px' } }"
                      :name="['conditions', index, 'result']"
                      required
                      :rules="[
                        {
                          required: true,
                          message: '请完善条件',
                          trigger: 'change'
                        }
                      ]"
                    >
                      <a-row :gutter="[16, 0]">
                        <a-col :span="8">
                          <a-form-item-rest>
                            <a-select
                              style="width: 100%"
                              v-model:value="subitem.eventType"
                              :disabled="modal.type === 'detail'"
                            >
                              <a-select-option
                                v-for="option in eventMaps"
                                :key="option.value"
                                :value="option.value"
                                >{{ option.label }}</a-select-option
                              >
                            </a-select>
                          </a-form-item-rest>
                        </a-col>
                        <a-col :span="12">
                          <a-input
                            :disabled="
                              !subitem.eventType ? true : modal.type === 'detail' ? true : false
                            "
                            v-model:value="subitem.result"
                            placeholder="请输入事件名称"
                            autocomplete="off"
                          />
                        </a-col>
                        <a-col :span="2" :offset="2">
                          <div class="icons">
                            <a-button
                              style="padding: 2px"
                              type="link"
                              danger
                              v-if="index"
                              @click="nodeDel(formState.conditions, index)"
                              :disabled="modal.type === 'detail'"
                              >删除</a-button
                            >
                            <!-- <DeleteOutlined
                              v-if="index"
                              @click="nodeDel(formState.conditions, index)"
                            /> -->
                            <a-button
                              style="padding: 2px"
                              type="link"
                              v-else
                              @click="nodeAdd(formState.conditions)"
                              :disabled="modal.type === 'detail'"
                              >新增</a-button
                            >
                            <!-- <PlusSquareOutlined v-else @click="nodeAdd(formState.conditions)" /> -->
                            <a-button
                              style="padding: 2px"
                              type="link"
                              @click="nodeCopy(formState.conditions, subitem)"
                              :disabled="modal.type === 'detail'"
                              >复制</a-button
                            >
                            <!-- <CopyOutlined @click="nodeCopy(formState.conditions, subitem)" /> -->
                          </div>
                        </a-col>
                      </a-row>
                    </a-form-item>
                  </template>
                </div>
              </a-col>
              <a-col :span="8">
                <div style=" height: 100%; padding: 16px;border: 1px solid #e5e6eb">
                  可选按钮
                  <a-form-item>
                    <div class="block" style=" min-height: 40px;border-width: 0">
                      <div v-if="modal.type === 'detail'" class="mask" />
                      <a-tag color="#e8f7ff" class="tag" @click="tagAdd('(')">(</a-tag>
                      <a-tag color="#e8f7ff" class="tag" @click="tagAdd(')')">)</a-tag>
                      <a-tag color="#e8f7ff" class="tag" @click="tagAdd('and')">and</a-tag>
                      <a-tag color="#e8f7ff" class="tag" @click="tagAdd('or')">or</a-tag>
                      <a-tag color="#e8f7ff" class="tag" @click="tagAdd('not')">not</a-tag>
                      <a-tag
                        color="#e8f7ff"
                        class="tag"
                        v-for="(item, index) in formState.conditions"
                        @click="tagAdd(`条件${numberToChinese(index + 1)}`)"
                        :key="index"
                        >{{ `条件${numberToChinese(index + 1)}` }}</a-tag
                      >
                    </div>
                  </a-form-item>
                  <span>编辑逻辑式</span>
                  <a-form-item
                    name="expression"
                    :rules="[
                      {
                        validator: expressValidator
                      }
                    ]"
                  >
                    <div class="block" style="margin-top: 8px">
                      <div v-if="modal.type === 'detail'" class="mask" />
                      <a-tag
                        color="#e8f7ff"
                        class="tag"
                        v-for="(tag, i) in formState.expression"
                        :key="i"
                        closable
                        >{{ tag }}</a-tag
                      >
                    </div>
                  </a-form-item>
                </div>
              </a-col>
            </a-row>
          </div>
          <template v-for="(item, index) in formState.pathManageTemplateVOList" :key="index">
            <a-form-item
              label="预警通知："
              :label-col="{ style: { width: '110px' } }"
              :name="['pathManageTemplateVOList', index, 'templateId']"
              required
              :rules="[
                {
                  required: true,
                  message: '请选择预警通知',
                  trigger: 'change'
                }
              ]"
            >
              <a-select
                v-model:value="item.templateId"
                @change="tempChange($event, item)"
                :disabled="modal.type === 'detail'"
                placeholder="请选择预警通知"
              >
                <a-select-option
                  v-for="option in tempMaps"
                  :key="option.value"
                  :value="option.value"
                  >{{ option.label }}</a-select-option
                >
              </a-select>
            </a-form-item>
            <a-row class="title" v-if="item.content">
              <a-col :span="24" style=" padding-left: 16px;background-color: #f7f8fa">
                <span class="red">*</span> 预警通知内容：
              </a-col>
            </a-row>
            <a-form-item v-if="item.content">
              <a-textarea
                style="width: 100%"
                :value="item.content"
                :maxlength="5000"
                :rows="5"
                disabled
              />
            </a-form-item>
          </template>

          <!-- <a-form-item v-if="modal.type !== 'detail'">
          <a-row>
            <a-button class="add" :icon="h(PlusOutlined)" @click="addNode">新增</a-button>
          </a-row>
        </a-form-item> -->
        </a-form>
        <template #footer>
          <template v-if="modal.type !== 'detail'">
            <a-button @click="modal.open = false">取消</a-button>
            <a-button :loading="modal.loading" type="primary" @click="modalConfirm">确认</a-button>
          </template>
          <template v-else>
            <!-- <a-button
            @click="modalUpdate"
            :disabled="formState.groupNames && formState.groupNames.length > 0 ? true : false"
            >编辑</a-button
          > -->
            <a-button type="primary" @click="modal.open = false">确认</a-button>
          </template>
        </template>
      </a-modal>
    </a-card>
  </div>
</template>

<script lang="ts" setup name="预警通知">
import Condition from '@/components/Condition/index.vue'
import { message, Modal } from 'ant-design-vue'
import { h, createVNode, onMounted } from 'vue'
import { timeFilter } from '@/utils/tools'
import {
  PlusSquareOutlined,
  CopyOutlined,
  DeleteOutlined,
  PlusOutlined,
  ExclamationCircleFilled
} from '@ant-design/icons-vue'
import {
  getWarningList,
  warningAdd,
  warningDel,
  getWarningTemplates,
  warningInfo
} from '@/api/warning'
import _ from 'lodash'
import { useDict } from './components/getDict'
import { numberToChinese } from '@/utils/tools'
import store from '@/store'

const { creatorList, init } = useDict(() => {
  getWarningTemplates().then((res) => {
    if (res.data) {
      tempMaps.value = res.data.map((v) => {
        v.label = v.templateName
        v.value = v.id
        return v
      })
    } else {
      tempMaps.value = []
    }
  })
})

const weeks = [
  {
    label: '周一',
    value: '周一'
  },
  {
    label: '周二',
    value: '周二'
  },
  {
    label: '周三',
    value: '周三'
  },
  {
    label: '周四',
    value: '周四'
  },
  {
    label: '周五',
    value: '周五'
  },
  {
    label: '周六',
    value: '周六'
  },
  {
    label: '周日',
    value: '周日'
  }
]

const tempMaps = ref([])

const eventMaps = [
  {
    label: '患者标签',
    value: '患者标签'
  }
]

const formState = reactive({
  id: '',
  createTime: '',
  noticeName: '',
  summary: '',
  conditions: [
    {
      // title: '条件一',
      eventType: '',
      result: ''
    }
  ],
  expression: [],
  pathManageTemplateVOList: [
    {
      templateId: undefined,
      templateName: '',
      templateType: '预警通知',
      content: ''
    }
  ]
})

const nodeAdd = (list) => {
  list.push({
    eventType: '',
    result: ''
  })
}

const nodeCopy = (list, item) => {
  list.push(_.cloneDeep(item))
}

const tagAdd = (str) => {
  formState.expression.push(str)
  modelForm.value?.clearValidate('expression')
}

const nodeDel = (list, index) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确认是否删除',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      list.splice(index, 1)
      formState.expression = []

      if (list.length == 1) {
        modelForm.value?.clearValidate('expression')
      }
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const expressValidator = async (_, value) => {
  if (formState.conditions.length >= 2) {
    if (!value.length) {
      return Promise.reject(new Error('请完善条件'))
    } else {
      return Promise.resolve()
    }
  } else {
    return Promise.resolve()
  }
}

const tNodeValidator = async (_, value) => {
  if (!value.templateId) {
    return Promise.reject('请完善内容')
  } else if ([3, 5].includes(value.templateType) && (!value.cronDate.length || !value.cronTime)) {
    return Promise.reject('请完善内容')
  } else {
    return Promise.resolve()
  }
}

const tempChange = (e, item) => {
  console.log(e, item)
  const i = tempMaps.value.find((v) => {
    return v.id === e
  })
  item.templateName = i.templateName
  item.content = i.content
}

const formState_reset = (item) => {
  modal.loading = false
  if (item) {
    Object.assign(formState, item)
  } else {
    Object.assign(formState, {
      id: '',
      createTime: '',
      noticeName: '',
      summary: '',
      conditions: [
        {
          // title: '条件一',
          eventType: '',
          result: ''
        }
      ],
      expression: [],
      pathManageTemplateVOList: [
        {
          templateId: undefined,
          templateName: '',
          templateType: '预警通知',
          content: ''
        }
      ]
    })
  }
}

const noticeName = ref('')

const condition = ref([
  {
    title: '创建者',
    dataIndex: 'creator',
    type: 'select',
    value: '',
    data: creatorList
  }
])
const conditionReset = () => {
  pagination.current = 1
  condition.value.map((v) => {
    v.value = ''
  })
  getList()
}

const pagination = reactive({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

const columns = ref([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: '50px'
  },
  {
    title: '预警通知名称',
    dataIndex: 'noticeName',
    key: 'noticeName',
    align: 'left',
    minWidth: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'left',
    width: '140px'
  },
  {
    title: '创建者',
    dataIndex: 'creator',
    key: 'creator',
    align: 'left',
    widht: '80px'
  },
  {
    title: '预警条件',
    dataIndex: 'conditionStr',
    key: 'conditionStr',
    align: 'left',
    minWidth: 200
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: '200px'
  }
])

const loading = ref(false)
const List = ref([])

const getList = () => {
  loading.value = true
  const { current, pageSize } = pagination
  const obj = condition.value.reduce((c, v) => {
    if (v.value || v.value === 0) {
      return Object.assign(c, { [v.dataIndex]: v.value })
    } else {
      return c
    }
  }, {})
  const params = {
    page: current,
    limit: pageSize,
    noticeName: noticeName.value,
    ...obj
  }
  getWarningList(params)
    .then((res) => {
      loading.value = false
      if (res.data.total > 0 && !res.data.list.length) {
        pagination.current = pagination.current - 1
        getList()
      } else {
        pagination.total = res.data.total
        List.value = res.data.list.map((v) => {
          v.conditionStr = JSON.parse(v.conditions).reduce((p, c) => {
            if (p) {
              return p + ',' + c.result
            } else {
              return c.result
            }
          }, '')
          return v
        })
      }
    })
    .catch((e) => {
      loading.value = false
    })
}

const paginationChange = (p) => {
  Object.assign(pagination, p)
  getList()
}

const onSearch = () => {
  pagination.current = 1
  getList()
}

onMounted(() => {
  getList()
})

const modal = reactive({
  open: false,
  type: 'save',
  loading: false,
  title: '新增预警通知'
})

const modalShow = (item) => {
  modelForm.value?.clearValidate()
  if (item) {
    warningInfo(item.id).then((res) => {
      console.log(res)
      modal.title = '预警通知详情'
      modal.type = 'detail'
      // const obj = convert({
      //   ...item,
      //   pathManageTemplateVOList: res.data.map((v) => {
      //     const index = tempMaps.findIndex((u) => {
      //       return u.value === v.templateType
      //     })
      //     return {
      //       templateId: v.templateId,
      //       templateName: v.templateName,
      //       templateType: v.templateType,
      //       templateTypeIndex: index,
      //       cronCycle: v.cronCycle,
      //       cronDate: v.cronDate,
      //       cronTime: v.cronTime
      //     }
      //   }, false)
      // })
      // res.data.pathManageTemplateVOList.map((v) => {
      //   const index = tempMaps.findIndex((u) => {
      //     return u.value === v.templateType
      //   })
      //   v.templateTypeIndex = index
      // })
      const obj = convert(res.data, false)
      console.log(obj)
      formState_reset(obj)
      modal.open = true
    })
  } else {
    modal.title = '新增预警通知'
    modal.type = 'save'
    formState_reset()
    modal.open = true
  }
}

const modelForm = ref(null)

const convert = (content, flag) => {
  const { id, createTime, noticeName, conditions, expression, pathManageTemplateVOList } =
    _.cloneDeep(content)
  if (flag) {
    const data = {
      id,
      createTime,
      noticeName,
      conditions: JSON.stringify(
        conditions.map((v, i) => {
          v.title = '条件' + numberToChinese(i + 1)
          return v
        })
      ),
      expression: expression.join(' '),
      pathManageTemplateVOList: pathManageTemplateVOList
    }
    return data
  } else {
    const data = {
      id,
      createTime,
      noticeName,
      conditions: JSON.parse(conditions).map((v) => {
        delete v.title
        return v
      }),
      expression: expression.split(' '),
      pathManageTemplateVOList: pathManageTemplateVOList
    }
    return data
  }
}

const modalConfirm = () => {
  // modal.loading = true
  modelForm.value
    .validate()
    .then(() => {
      console.log('表单验证通过')
      const params = convert(formState, true)

      if (formState.conditions.length === 1) {
        params.expression = '条件一'
      }

      if (modal.type === 'save') {
        warningAdd(params)
          .then((res) => {
            message.success('新建成功')
            modal.loading = false
            modal.open = false
            conditionReset()
            init()
          })
          .catch((e) => {
            modal.loading = false
          })
      } else {
        warningUpdate(params)
          .then((res) => {
            message.success('编辑成功')
            modal.loading = false
            modal.open = false
            getList()
          })
          .catch((e) => {
            modal.loading = false
          })
      }
    })
    .catch((e) => {
      console.log(e)
    })
}

const modalUpdate = () => {
  modal.type = 'update'
  modal.title = '编辑预警通知'
}

const Del = (item) => {
  Modal.confirm({
    title: '删除',
    class: 'confirm',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确定删除该通知么',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      warningDel(item.id).then(() => {
        message.success('删除成功')
        init()
        getList()
      })
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}
</script>

<style lang="less" scoped>
@import url('@/views/warning/index.less');

.header {
  display: flex;
  flex: 0 0 auto;
  flex-direction: row;
  justify-content: space-between;

  .left {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row;
      align-items: center;
    }

    .title {
      font-size: 14px;
      font-weight: 400;
      line-height: 32px;
      color: #4e5969;
    }
  }

  .right {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
    }
  }
}

.main {
  flex: 1 1 auto;
  margin-top: 16px;
  overflow: hidden auto;

  :deep(.ant-table-wrapper) {
    .ant-table-cell {
      p {
        margin-bottom: 0;
        white-space: normal;

        .configuration {
          display: inline-block;
          max-width: 100%;
          margin-top: 10px;
          overflow: hidden;
          color: #3491fa;
          text-overflow: ellipsis;
          white-space: nowrap;
          background: #e8f7ff;
          border-color: #3491fa;

          &:nth-child(1) {
            margin-top: 0;
          }
        }

        .success {
          display: inline-block;
          max-width: 100%;
          margin-top: 10px;
          overflow: hidden;
          color: #00b42a;
          text-overflow: ellipsis;
          white-space: nowrap;
          background: #e8ffea;
          border-color: #00b42a;

          &:nth-child(1) {
            margin-top: 0;
          }
        }

        .groupTag {
          display: inline-block;
          max-width: 100%;
          margin-top: 10px;
          margin-right: 10px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;

          &:nth-child(1) {
            margin-top: 0;
          }
        }
      }
    }
  }
}

.input {
  width: 210px !important;
}

.modelForm {
  .bar {
    margin-bottom: 12px;
    border: 1px solid #e5e6eb;
  }

  .node {
    padding-bottom: 1px;
    margin: 0 0 10px;
    background: #f7f8fa;

    .ant-form-item {
      margin-bottom: 8px;
    }
  }

  .red {
    color: #f56667;
  }

  .title {
    width: 100%;
    height: 32px;
    margin-bottom: 16px;
    font-size: 14px;
    font-weight: 500;
    line-height: 32px;
  }

  .add {
    // width: 1160px;
    height: 32px;
    font-size: 14px;
    font-weight: 400;
    line-height: 22px;
    color: #165dff;
    border-color: #165dff;
  }

  .icon-plus,
  .icon-del {
    font-size: 16px;
  }

  .icon-plus {
    color: #165dff;
  }

  .icon-del {
    color: #f53f3f;
  }
}

.row {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
}

.ant-form .ant-input {
  width: 100% !important;
}

.icons {
  display: flex;
  flex-direction: row-reverse;
  gap: 6px;
  align-items: center;
  width: 100%;
  height: 100%;
  font-size: 20px;
}

.block {
  position: relative;
  display: flex;
  flex-flow: row wrap;
  gap: 6px;
  align-content: flex-start;
  width: 100%;
  min-height: 88px;
  padding: 6px;
  overflow: hidden auto;
  border: 1px solid #e5e6eb;

  .mask {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 99;
    width: 100%;
    height: 100%;
  }

  .tag {
    margin-right: 0;
    cursor: pointer;
  }
}

.groups {
  display: flex;
  flex-flow: row wrap;
  gap: 6px;
  width: 280px;
}
</style>
